package com.cheng.chengrobot.handler.gptHandler;

import com.cheng.chengrobot.domain.GptChatHistory;
import com.cheng.chengrobot.service.RobotFriendService;
import com.cheng.chengrobot.service.RobotService;
import com.cheng.chengrobot.service.gpt.AiRequest;
import com.cheng.chengrobot.service.gpt.GptChatHistoryService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.FriendMessageEvent;
import net.mamoe.mirai.message.data.*;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class FriendGptHandler
        extends SimpleListenerHost
{

    @Autowired
    private RobotFriendService robotFriendService;
    @Autowired
    private RobotService robotService;
    @Autowired
    private GptChatHistoryService gptChatHistoryService;
    @Autowired
    private ObjectMapper objectMapper;
    @Value("${gpt.api-key}")
    private String apiKey;
    @Value("${gpt.system-message}")
    private String systemMessage;
    @Autowired
    @Qualifier("proxyOkHttp")
    private OkHttpClient.Builder okHttpClientBuilder;

    @Autowired
    AiRequest aiRequest;

    @EventHandler
    public void handleFriendMessage(@NotNull FriendMessageEvent event)
            throws Exception
    {
        System.out.println(1);
        if (!(robotFriendService.isGptTurnedOn(event.getBot().getId(), event.getFriend().getId())
                && robotService.isChatGptTurnedOn(event.getBot().getId()))) return;
        System.out.println(2);

        //合成消息的字符串
        MessageChain messageChain = event.getMessage();
        String messageStr = "";
        for (SingleMessage singleMessage : messageChain)
        {
            messageStr += singleMessage.contentToString();
        }
        //制作消息记录持久化存储到数据库
        GptChatHistory gptChatHistory = new GptChatHistory();
        gptChatHistory.setMessage(messageStr);
        gptChatHistory.setRole("user");
        gptChatHistory.setRobotQq(event.getBot().getId());
        gptChatHistory.setQq(event.getFriend().getId());
        this.gptChatHistoryService.insert(gptChatHistory);


        //制作请求体，选取过去的5轮对话
        //构建json节点
        ObjectNode requestBodyJson = objectMapper.createObjectNode().put("model", "gpt-3.5-turbo");
        ArrayNode messagesJson = objectMapper.createArrayNode();
        //加入系统消息
        messagesJson.add(objectMapper.createObjectNode()
                                 .put("role", "system")
                                 .put("content", systemMessage));


        List<GptChatHistory> gptChatHistories = this.gptChatHistoryService.selectRecentTen(event.getBot().getId(),
                                                                                           null,
                                                                                           event.getSender().getId());
        //循环往节点里面加入消息
        for (int i = 0; i < gptChatHistories.size(); i++)
        {
            messagesJson.add(objectMapper.createObjectNode()
                                     .put("role", gptChatHistories.get(gptChatHistories.size() - i - 1).getRole())
                                     .put("content",
                                          gptChatHistories.get(gptChatHistories.size() - i - 1).getMessage()));
        }


        requestBodyJson.set("messages", messagesJson);
        JsonNode responseJson = objectMapper.readTree(aiRequest.callGpt(requestBodyJson.toString()));


        gptChatHistory.setNull();
        gptChatHistory.setRole(responseJson.get("choices").get(0).get("message").get("role").asText());
        gptChatHistory.setMessage(responseJson.get("choices").get(0).get("message").get("content").asText());
        gptChatHistory.setRobotQq(event.getBot().getId());
        gptChatHistory.setQq(event.getSender().getId());

        //回复好友
        event.getSubject().sendMessage(gptChatHistory.getMessage());

        //存储回复
        this.gptChatHistoryService.insert(gptChatHistory);


    }
}
